package com.xzt.bookstore.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzt.bookstore.common.Result;
import com.xzt.bookstore.dto.BookCreateRequest;
import com.xzt.bookstore.entity.Book;
import com.xzt.bookstore.service.BookService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 图书控制器
 */
@RestController
@RequestMapping("/api/books")
@RequiredArgsConstructor
public class BookController {
    
    private final BookService bookService;
    
    /**
     * 获取图书列表（分页）
     */
    @GetMapping
    public Result<Page<Book>> getBookList(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String author,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) Integer status) {
        
        Page<Book> page = bookService.getBookList(current, size, name, author, category, status);
        return Result.success(page);
    }
    
    /**
     * 根据ID获取图书详情
     */
    @GetMapping("/{id}")
    public Result<Book> getBookById(@PathVariable Long id) {
        Book book = bookService.getById(id);
        if (book == null) {
            return Result.error(404, "图书不存在");
        }
        return Result.success(book);
    }
    
    /**
     * 创建图书
     */
    @PostMapping
    public Result<Book> createBook(@Valid @RequestBody BookCreateRequest request) {
        try {
            Book book = bookService.createBook(request);
            return Result.success("图书创建成功", book);
        } catch (Exception e) {
            return Result.error("创建图书失败：" + e.getMessage());
        }
    }
    
    /**
     * 下架图书
     */
    @PutMapping("/{id}/offline")
    public Result<Book> offlineBook(@PathVariable Long id) {
        try {
            Book book = bookService.offlineBook(id);
            return Result.success("图书下架成功", book);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("下架图书失败：" + e.getMessage());
        }
    }
}

